package repository

import (
	"gitee.com/duan_shengjie/category/domain/model"
	"github.com/jinzhu/gorm"
)

type ICategoryRepository interface {
	InitTable() error
	Add(*model.Category) (int64, error)
	Delete(int64) error
	Update(*model.Category) error
	FindById(int64) (*model.Category, error)
	FindByName(string) (*model.Category, error)
	FindAll() ([]*model.Category, error)
	FindByLevel(uint32) ([]*model.Category, error)
	FindByParent(int64) ([]*model.Category, error)
}

type CategoryRepository struct {
	mysqlDb *gorm.DB
}

func NewCategoryRepository(db *gorm.DB) *CategoryRepository {
	return &CategoryRepository{mysqlDb: db}
}

func (c *CategoryRepository) InitTable() error {
	return c.mysqlDb.CreateTable(&model.Category{}).Error
}

func (c *CategoryRepository) Add(m *model.Category) (int64, error) {
	return m.ID, c.mysqlDb.Create(m).Error
}

func (c *CategoryRepository) Delete(id int64) error {
	return c.mysqlDb.Where("id = ?", id).Delete(&model.Category{}).Error
}

func (c *CategoryRepository) Update(m *model.Category) error {
	return c.mysqlDb.Model(m).Update(m).Error
}

func (c *CategoryRepository) FindById(id int64) (*model.Category, error) {
	m := new(model.Category)
	return m, c.mysqlDb.Where("id = ?", id).Find(m).Error
}

func (c *CategoryRepository) FindByName(categoryName string) (*model.Category, error) {
	m := new(model.Category)
	return m, c.mysqlDb.Where("category_name = ?", categoryName).Find(m).Error
}

func (c *CategoryRepository) FindAll() (m []*model.Category, err error) {
	return m, c.mysqlDb.Find(&m).Error
}

func (c *CategoryRepository) FindByLevel(level uint32) (m []*model.Category, err error) {
	return m, c.mysqlDb.Where("category_level = ?", level).Find(&m).Error
}

func (c *CategoryRepository) FindByCategoryName(categoryName string) (m []*model.Category, err error) {
	return m, c.mysqlDb.Where("category_name = ?", categoryName).Find(&m).Error
}

func (c *CategoryRepository) FindByParent(parentId int64) (m []*model.Category, err error) {
	return m, c.mysqlDb.Where("category_parent = ?", parentId).Find(&m).Error
}
